/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.module.login

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_login.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import top.stime21.framework.extension.showToast
import top.stime21.framework.extension.toActivityWithSerializable
import top.stime21.myneighbours.Events
import top.stime21.myneighbours.R
import top.stime21.myneighbours.utils.CheckUtils

class LoginActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        EventBus.getDefault().register(this)
        phoneEdit.addTextChangedListener(editAction)
        btn_getsms.setOnClickListener({
            var phoneStr = phoneEdit.text.toString()
            if(TextUtils.isEmpty(phoneStr)){
                showToast("请输入手机号码")
                return@setOnClickListener
            }
            if(!CheckUtils.isChinaPhoneLegal(phoneStr)){
                showToast("请正确的手机号码")
                return@setOnClickListener
            }
            toActivityWithSerializable<CheckSmsActivity>(phoneStr)
        })
    }
    private val editAction :TextWatcher = object: TextWatcher {
        override fun afterTextChanged(p0: Editable?) {

        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, count: Int) {
            Logger.i("onTextChanged${count}")
            if(p0!=null && p0!!.length==11){
                btn_getsms.isEnabled=true
            }else{
                btn_getsms.isEnabled=false
            }
        }


    }
    @Subscribe
    fun onRecvLoginEvent(e:Events.Login){
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

}
